import { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import dayjs from 'dayjs';
import loadable from '@loadable/component';

import useDevice, { DEVICES } from '@/hooks/useDevice';
import { getKeyFromUrl } from '@/utils';
import { WEEK_TOP, WORK_DETAIL, ROLE_DETAIL } from '@/config/url';
import { getHotWorkList, getHotRoleList } from '@/service/api';
import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));
const Empty = loadable(() => import('@/components/Empty'));
/*
    rank 排名
    rankChange 排名变化，正数代表上升了几位、负数代表下降，0没有变化
    score 统计的浏览数
    id 主键
    name 名称
    mainImage 主图
*/
export default props => {
    const [ type, setType ] = useState(props.type || '');
    const [ items, setItems ] = useState([]);
    const navigate = useNavigate();
    const location = useLocation();
    const isMobile = useDevice() === DEVICES.MOBILE;

    // 获取数据
    const getDataList = async (currentType) => {
        try{
            const api = currentType === 'works' ? getHotWorkList : getHotRoleList;
            const [res, err] = await api();
            setItems(res?.data || []);
        } catch(err) {
            console.log(err);
        }
    };

    // 跳转详情页
    const toDetail = id => {
        navigate(`${type === 'works' ? WORK_DETAIL : ROLE_DETAIL}?id=${id}`);
    };

    const scoreElement = (item, onlyScore=false) => {
        const s = item.rankChange ? (item.rankChange > 0 ? 1 : -1) + item.rankChange : '';

        return (
            <div className={`${styles['rank-badge']} ${styles[s<0?'down':'up']}`}>
                <div className={styles['trend']} style={onlyScore?{padding:0}:{}}>
                    <IconFont name={`icon-${s<0?'down':'up'}`}/>
                </div>
                <div className={styles['rank']}>
                    <span>{Math.abs(item.rankChange)}</span>
                    {/* <span>{item.score}</span> */}
                    {/* {onlyScore ? null : <sup>{s<0?'-':'+'}{Math.abs(item.rankChange)}</sup>} */}
                </div>
            </div>
        );
    };
    // 监听 location 变化，获取 type 参数
    useEffect(() => {
        const searchParams = new URLSearchParams(location.search);
        const typeParam = searchParams.get('type');
        
        if(typeParam && ['works', 'roles'].includes(typeParam)) {
            setType(typeParam);
        }
    }, [location.search]);

    // 当 type 变化时，重新获取数据
    useEffect(() => {
        if (type) getDataList(type);
    }, [type]);

    const top1to3 = items.slice(0, 3);
    const top4to10 = items.slice(3, 10);
    const top11to20 = items.slice(10, 20);

    return (
        <div className={styles['container']}>
            <div className={styles['title']}>本周热门{type === 'works' ? '作品' : '角色'}TOP20</div>

            {
                !top1to3.length && !top4to10.length && !top11to20.length ?
                    <Empty/>
                    :
                    null
            }
            <div className={styles['top']}>
                {top1to3.map(item => {
                    const s = item.rankChange ? (item.rankChange > 0 ? 1 : -1) + item.rankChange : '';

                    return (
                        <div key={item.id} className={styles['big-card']} onClick={toDetail.bind(null, item.id)}>
                            <div className={styles['thumb-lg']} style={{'--height': isMobile ? '100px' : '240px'}}>
                                <img src={item.mainImage || '/images/image-holder.svg'} alt={item.name} />
                                { scoreElement(item) }
                            </div>
                            <div className={styles['name-line']}>
                                <span className={styles['name']}>{item.name}</span>
                            </div>
                        </div>
                    );
                })}
            </div>

            { top4to10.length ? <div className={styles['divider']}></div> : null }

            <div className={styles['mid']}>
                {top4to10.map(item => {
                    const s = item.rankChange ? (item.rankChange > 0 ? 1 : -1) + item.rankChange : '';

                    return (
                        <div key={item.id} className={styles['mid-item']} onClick={toDetail.bind(null, item.id)}>
                            <div className={styles['mid-left']}>
                                <span className={styles['rank']}>{item.rank}</span>
                                <div className={styles['thumb-sm']}>
                                    <img src={item.mainImage ? `${item.mainImage}?x-oss-process=image/resize,p_20` : '/images/image-holder.svg'} alt={item.name} />
                                </div>
                            </div>
                            <div className={styles['mid-right']}>
                                <span className={styles['name']}>{item.name}</span>
                            </div>
                            { scoreElement(item) }
                        </div>
                    );
                })}
            </div>

            {top11to20.length ? <div className={styles['divider']}></div> : null}

            <div className={styles['mid']}>
                {top11to20.map(item => {
                    return (
                        <div key={item.id} className={styles['mid-item']} onClick={toDetail.bind(null, item.id)}>
                            <div className={styles['mid-left']}>
                                <span className={styles['rank']}>{item.rank}</span>
                            </div>
                            <div className={styles['mid-right']}>
                                <span className={styles['name']}>{item.name}</span>
                            </div>
                            { scoreElement(item, true) }
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
